package com.example.demo.controller;


import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.dto.PageReqDTO;
import com.example.demo.entity.*;
import com.example.demo.service.UserService;
import com.example.demo.utils.DateUtil;
import com.example.demo.utils.TokenUtils;
import com.example.demo.vo.UserVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


/**
 * 用户控制器
 *
 * @author He Dong
 * @date 2023/12/12
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 分页获取获取用户信息
     *
     * @return {@code List<User>}
     */
    @GetMapping("/list")
    public Result selectAll(Integer current, Integer size) {
        IPage<UserVo> list = userService.selectPage(new Page<>(current, size));
        return Result.success(list);
    }


    /**
     * 按关键字获取用户信息
     *
     * @param keyWords 关键词
     * @param state    状态
     * @return {@code User}
     */
    @GetMapping("/selectKeyWords")
    public Result selectByAccount(String keyWords, Integer state) {
        if (state == 1) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("account", keyWords);
            return Result.success(userService.getOne(wrapper));
        } else {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.like("name", keyWords);
            return Result.success(userService.list(wrapper));
        }
    }


    /**
     * 获取用户信息
     *
     * @return {@code Result}
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                String account = JWT.decode(token).getAudience().get(0);
                QueryWrapper<User> wrapper = new QueryWrapper<>();
                wrapper.eq("account", account);
                User user = userService.getOne(wrapper);
                UserVo userVo = new UserVo();
                userVo.setId(user.getId());
                userVo.setAvatar(user.getAvatar());
                userVo.setName(user.getName());
                userVo.setAccount(user.getAccount());
                userVo.setRoleId(user.getRoleId());
                userVo.setPhone(user.getPhone());
                userVo.setMailbox(user.getMailbox());
                userVo.setWechat(user.getWechat());
                userVo.setQq(user.getQq());
                userVo.setLoginTime(user.getLoginTime());
                userVo.setLogoutTime(user.getLogoutTime());
                userVo.setCreateTime(user.getCreateTime());
                return Result.success(userVo);
            }
        } catch (Exception e) {
            return Result.error();
        }
        return Result.error();
    }


    /**
     * 添加/修改用户信息
     *
     * @param user 用户
     * @return {@code Result}
     */
    @PostMapping("/doAdd")
    public Result doAdd(@RequestBody User user) {
        if (user.getId() != null) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("id", user.getId());
            User repeat = userService.getOne(wrapper);
            if (!repeat.getAccount().equals(user.getAccount())){
                    return Result.error("409", "账号重复");
            }
            UpdateWrapper<User> wrapper1 = new UpdateWrapper<>();
            wrapper1.eq("id", user.getId());
            userService.update(user, wrapper1);
            return Result.success("用户编辑成功");
        } else {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("account", user.getAccount());
            User repeat = userService.getOne(wrapper);
            if (repeat != null) {
                return Result.error("409", "账号重复");
            }
            user.setCreateTime(DateUtil.getDate());
            userService.save(user);
            return Result.success("用户添加成功");
        }
    }

    /**
     * 上传图片
     *
     * @param file 文件
     * @param id   编号
     * @return {@code Result}
     */
    @PostMapping("uploadImage")
    public Result uploadImage(@RequestParam MultipartFile file, @RequestParam Integer id) {
        // 检查图片是否为空
        if (file.isEmpty()) {
            return Result.error("400", "请选择要上传的图片");
        }
        try {
            // 获取图片信息
            byte[] data = file.getBytes();
            User user = userService.getById(id);
            user.setAvatar(data);
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            userService.update(user, wrapper);
            // 创建ImageInfo对象并保存到数据库
            return Result.success("图片上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("图片上传失败");
        }
    }

    /**
     * 删除用户信息
     *
     * @param id 用户id
     * @return {@code Result}
     */
    @DeleteMapping("delete")
    public Result delete(Integer id) {
        boolean res = userService.removeById(id);
        if (res) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }


}

